/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-04-20
*/
package com.rzico.basics.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Shop;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.ShopService;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysReport;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysReportService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.util.FreemarkerUtils;
import com.rzico.util.HttpUtils;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.engine.JRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计报表控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-04-20
 */
@Api(description = "统计报表接口")
@RestController
@RequestMapping("/report")
public class ReportController extends BaseController {

    @Autowired
    private SysReportService sysReportService;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private EnterpriseService enterpriseService;


    @Value("${rzico.filePath.windows}")
    private String windowsFilePath;

    @Value("${rzico.filePath.linux}")
    private String linuxFilePath;

    /**
     *  报表打印
     *
     * @param id
     * @return
     */
    @ApiOperation("报表打印")
    @GetMapping("/print/{id}")
    public void print(HttpServletRequest request, HttpServletResponse response, @PathVariable String id,String beginDate, String endDate)
            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");

        Map<String, Object> param = new HashMap<String, Object>();
        param = HttpUtils.requestParam(request);
        logger.info("打印报表查询参数：{}", param.toString());
        SysReport sysReport = sysReportService.selectByPrimaryKey(id);
        if (null == sysReport){
            throw new CustomException("报表不存在");
        }

        Enterprise enterprise = enterpriseService.findByMch(sysReport.getMchId());
        if (null == enterprise) {
            throw new CustomException("没有开通企业");
        }

        if (null != param.get("shopId") || "".equals(param.get("shopId"))){
            Shop shop = shopService.selectByPrimaryKey(param.get("shopId"));
            if (null != shop){
                param.put("shopName", shop.getName());
            }
        }

        param.put("enterpriseId",enterprise.getId());

        String sql = sysReport.getSql();
        logger.info("未转化的报表sql：{}", sql);
        try {
            sql = FreemarkerUtils.process(sql, param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("解释SQL出错了");
        }
        logger.info("转换后的报表sql：{}", sql);
        //根据reportName下载文件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = sysReport.getId()+"_"+sdf.format(sysReport.getModifyDate()) + ".jasper";

        String filePath = "";
        if (System.getProperty("os.name").contains("Windows")) {
            filePath = windowsFilePath;
        } else if (System.getProperty("os.name").contains("Linux")) {
            filePath = linuxFilePath;
        } else {
            filePath = System.getProperty("java.io.tmpdir");
        }

        File file = new File(filePath + File.separator + fileName);
        if (!file.exists()){
            try {
                sysReportService.fileDownLoad(response, sysReport.getTemplate(), filePath, fileName);
            } catch (Exception e){
                logger.info("打印模板下载失败");
                throw new CustomException("打印模板下载失败");
            }
        }

        SysMch sysMch = sysMchService.findById(sysReport.getMchId());
        param.put("COMPANY",sysMch.getName());
        param.put("REPORT_NAME", sysReport.getName());
        sysReportService.commReportToPdf(filePath, fileName, param, sql.toString(), response);
    }


    /**
     *  订单打印
     *
     * @param id
     * @return
     */
    @ApiOperation("导出订单")
    @GetMapping("/export/{id}")
    public void export(HttpServletRequest request, HttpServletResponse response, @PathVariable String id)
            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");

        Map<String, Object> param = new HashMap<String, Object>();

        param = HttpUtils.requestParam(request);
        logger.info("打印报表查询参数：{}", param.toString());
        SysReport sysReport = sysReportService.selectByPrimaryKey(id);
        if (null == sysReport){
            throw new CustomException("报表不存在");
        }


        Enterprise enterprise = enterpriseService.findByMch(sysReport.getMchId());
        if (null == enterprise) {
            throw new CustomException("没有开通企业");
        }

        if (null != param.get("shopId") || "".equals(param.get("shopId"))){
            Shop shop = shopService.selectByPrimaryKey(param.get("shopId"));
            if (null != shop){
                param.put("shopName", shop.getName());
            }
        }

        param.put("enterpriseId",enterprise.getId());

        String sql = sysReport.getSql();
        logger.info("未转化的报表sql：{}", sql);
        try {
            sql = FreemarkerUtils.process(sql, param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("解释SQL出错了");
        }
        logger.info("转换后的报表sql：{}", sql);
        //根据reportName下载文件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = sysReport.getId()+"_"+sdf.format(sysReport.getModifyDate())+ ".jasper";

        String filePath = "";
        if (System.getProperty("os.name").contains("Windows")) {
            filePath = windowsFilePath;
        } else if (System.getProperty("os.name").contains("Linux")) {
            filePath = linuxFilePath;
        } else {
            filePath = System.getProperty("java.io.tmpdir");
        }

        File file = new File(filePath + File.separator + fileName);
        if (!file.exists()){
            try {
                sysReportService.fileDownLoad(response, sysReport.getTemplate(), filePath, fileName + ".jasper");
            } catch (Exception e){
                logger.info("打印模板下载失败");
                throw new CustomException("打印模板下载失败");
            }
        }

        SysMch sysMch = sysMchService.findById(sysReport.getMchId());
        param.put("COMPANY",sysMch.getName());
        param.put("REPORT_NAME", sysReport.getName());

        sysReportService.commReportToExcelBySql(filePath, fileName, param, sql.toString(), response);
    }

}
